package com.chy.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.commonutils.JwtUtils;
import com.chy.commonutils.Result;
import com.chy.order.pojo.TOrder;
import com.chy.order.service.OrderService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author chy
 * @since 2020-11-02
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "根据课程id，用户id生成订单")
    @PostMapping("createOrder/{courseId}")
    public Result saveOrder(@ApiParam(name = "courseId", value = "课程ID", required = true)
                                  @PathVariable String courseId, HttpServletRequest request)
    {
        // 创建订单，返回订单号
        String orderNo = orderService.createOrders(courseId,JwtUtils.getMemberIdByJwtToken(request));
        return Result.ok().data("orderId",orderNo);
    }

    @ApiOperation(value = "根据订单id查询订单信息")
    @GetMapping("getOrderInfo/{orderId}")
    public Result getOrderInfo(@ApiParam(name = "orderId", value = "订单ID", required = true)
                                   @PathVariable String orderId)
    {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        TOrder tOrder = orderService.getOne(wrapper);
        return Result.ok().data("item", tOrder);
    }

    @ApiOperation(value = "根据课程id和用户id查询订单表中订单状态")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@ApiParam(name = "courseId", value = "课程ID", required = true)
                                   @PathVariable String courseId,
                               @ApiParam(name = "memberId", value = "用户ID", required = true)
                                   @PathVariable String memberId)
    {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if (count > 0) { // 已经支付
            return true;
        } else {
            return false;
        }
    }
}

